﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using CObject;
using ConnectionServer;
using Objects.CMT;
using Objects.Utility;

public partial class CreateAnEvent : Objects.cSecurePage
{
    DataTable eventstable;
    DataTable eventresult;
    DataTable eventattendee;
    private bool isQuestionsLocked = false;

    #region const

    private const string OWN_CLIENT = "Client";
    private const string OWN_PARTICIPANT = "OwnClient";
    private const string OWN_YES = "Yes";
    private const string OWN_NO = "No";
    private const int ATTENDEE_UPLOAD_COLUMN_COUNT = 25;

    private const string ROOM_SAVE = "Room successfully saved.";
    private const string ROOM_NAME_EXIST = "Room Name already exists.";
    private const string QUESTION_SAVE = "All selected questions successfully saved against the event. If no questions are selected, it means no questions to assign against the event.";
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        CMTEvent events = new CMTEvent();

        Page.Form.Attributes.Add("enctype", "multipart/form-data");
        #region Event registrations
        btnCreateEvent.Click += new EventHandler(btnCreateEvent_Click);
        btnClear.Click += new EventHandler(btnClear_Click);
        btnSearch.Click += new EventHandler(btnSearch_Click);
        btnClearEventSearch.Click += new EventHandler(btnClearEventSearch_Click);
        btnAddUsers.Click += new EventHandler(btnAddUsers_Click);
        btnRemoveUsers.Click += new EventHandler(btnRemoveUsers_Click);

        //Validators              
        btnDeleteAttendee.Click += new EventHandler(btnDeleteAttendee_Click);
        btnAddAttendee.Click += new EventHandler(btnAddAttendee_Click);
        btnClearAttendee.Click += new EventHandler(btnClearAttendee_Click);
        UploadButton.Click += new EventHandler(UploadButton_Click);
        btnSearchAttendee.Click += new EventHandler(btnSearchAttendee_Click);
        btnRight.Click += new EventHandler(btnRight_Click);
        btnLeft.Click += new EventHandler(btnLeft_Click);
        btnAllLeft.Click += new EventHandler(btnAllLeft_Click);
        btnAllRight.Click += new EventHandler(btnAllRight_Click);

        #endregion

        lblSearchAttendee.Visible = false;
        lbUploadAttendee.Visible = false;
        lbAddAttendee.Visible = false;
        lblEventMessage.Visible = false;
        lbFailedInsert.Visible = false;
        lblFieldAdminMsg.Visible = false;
        StatusLabel.Visible = false;
        divAttendeeUpload.Visible = false;

        //questions linked
        isQuestionsLocked = false;
        lblQuestions.Visible = false;
        btnSaveQuestions.Enabled = true;
        btnSelectAll.Enabled = true;

        if (!IsPostBack)
        {
            #region Intial Data bind

            ddlCountry.DataSource = events.GetCountryDetails();
            ddlCountry.DataTextField = "Description";
            ddlCountry.DataValueField = "COUNTRY";
            ddlCountry.DataBind();

            ddlCountry.Items.Insert(0, new ListItem("Select Country", String.Empty));
            ddlCountry.SelectedIndex = 0;

            ddl2Country.DataSource = events.GetCountryDetails();
            ddl2Country.DataTextField = "Description";
            ddl2Country.DataValueField = "COUNTRY";
            ddl2Country.DataBind();

            ddl2Country.Items.Insert(0, new ListItem("Select Country", String.Empty));
            ddl2Country.SelectedIndex = 0;

            bindCountryList();

            ddlTimeZones.DataSource = GetTimeZonesItems();
            ddlTimeZones.DataTextField = "DisplayName";
            ddlTimeZones.DataValueField = "Offset";
            ddlTimeZones.DataBind();

            //bind events to search grid.
            bindEventsGridView();
            #endregion
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "settabs", "SetTabs()", true);
    }

    #region Events

    private DataTable GetTimeZonesItems()
    {
        DataTable timezones = new DataTable();
        timezones.Columns.Add("Offset", typeof(string));
        timezones.Columns.Add("DisplayName", typeof(string));

        var timeZoneNames = TimeZoneInfo.GetSystemTimeZones();
        var items = new List<ListItem>();
        foreach (TimeZoneInfo zone in timeZoneNames)
        {
            timezones.Rows.Add((zone.BaseUtcOffset.Hours >= 0 ? "+" : "") + zone.BaseUtcOffset.Hours.ToString("00") + ":" + zone.BaseUtcOffset.Minutes.ToString("00").TrimStart('-'), zone.DisplayName);
        }
        return timezones;
    }

    protected void wgData_ItemCommand(object sender, GridViewCommandEventArgs e)
    {

        CMTEvent events = new CMTEvent();
        int eventId = Convert.ToInt32(e.CommandArgument);
        //set hidden field with event id
        hdnFieldEventID.Value = eventId.ToString();
        empLookUp.Text = string.Empty;
        empLookUp.value = string.Empty;

        #region Edit Event
        if (e.CommandName.Equals("Edit Event"))
        {

            //binding existing event data to controls 
            if (String.IsNullOrEmpty(hdnFieldEventID.Value) == false)
            {
                eventresult = events.GetSpecificEvent(int.Parse(hdnFieldEventID.Value));
                txtEventName.Text = decodeString(eventresult.Rows[0]["EventName"]);
                txtEventDescription.Text = decodeString(eventresult.Rows[0]["EventDescription"]);

                ListItem timezoneselected = ddlTimeZones.Items.FindByValue(eventresult.Rows[0]["UTCTimeZoneOffset"].ToString());
                if (timezoneselected != null)
                {
                    ddlTimeZones.ClearSelection();
                    timezoneselected.Selected = true;
                }

                ListItem selectedListItem = ddlCountry.Items.FindByValue(eventresult.Rows[0]["Country"].ToString());
                if (selectedListItem != null)
                {
                    ddlCountry.ClearSelection();
                    selectedListItem.Selected = true;
                }

                txtStartDate.Text = DateTime.Parse(eventresult.Rows[0]["StartDate"].ToString()).ToString("MMMM d, yyyy");

                ListItem starthr = ddlStartTimeHrs.Items.FindByValue(DateTime.Parse(eventresult.Rows[0]["StartDate"].ToString()).ToString("HH"));
                if (starthr != null)
                {
                    ddlStartTimeHrs.ClearSelection();
                    starthr.Selected = true;
                }

                ListItem startmm = ddlStartTimeMns.Items.FindByValue(DateTime.Parse(eventresult.Rows[0]["StartDate"].ToString()).ToString("mm"));
                if (startmm != null)
                {
                    ddlStartTimeMns.ClearSelection();
                    startmm.Selected = true;
                }

                txtEndDate.Text = DateTime.Parse(eventresult.Rows[0]["EndDate"].ToString()).ToString("MMMM d, yyyy");

                ListItem endhr = ddlEndhour.Items.FindByValue((DateTime.Parse(eventresult.Rows[0]["EndDate"].ToString()).ToString("HH")));
                if (endhr != null)
                {
                    ddlEndhour.ClearSelection();
                    endhr.Selected = true;
                }

                ListItem endmm = ddlEndMinute.Items.FindByValue(DateTime.Parse(eventresult.Rows[0]["EndDate"].ToString()).ToString("mm"));
                if (endmm != null)
                {
                    ddlEndMinute.ClearSelection();
                    endmm.Selected = true;
                }

                lstAdmins.Items.Clear();
                if (string.IsNullOrEmpty(eventresult.Rows[0]["XMLAdmins"].ToString()) == false)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(eventresult.Rows[0]["XMLAdmins"].ToString());
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList nodes = root.SelectNodes("FieldAdmin");

                    foreach (XmlNode node in nodes)
                    {
                        lstAdmins.Items.Add(new ListItem(node.ChildNodes[1].InnerText, node.ChildNodes[0].InnerText));
                    }
                }
                ViewState["isQuestionConfigured"] = Convert.ToBoolean(eventresult.Rows[0]["IsQuestionConfigured"]);
            }

            ClearUploadAttendee();
            ClearSearchAttendee();
            ClearAttendeeEdit();
            clearRoom();
            bindEventRooms();
            div_Attendee.Visible = true;
            bindAttendee();
            bindEventsGridView();
            bindQuestions();
            // updAttendee.Update();
            uproom.Update();
            updEditEvent.Update();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "changeactivetab", "ChangeTab()", true);
        }
        #endregion

        #region Edit Meeting redirect

        if (e.CommandName.Equals("Edit Meeting"))
        {
            Session["EventID"] = eventId;
            HttpContext.Current.Response.Redirect("./MeetingCreation.aspx");
        }
        #endregion
    }

    void btnRemoveUsers_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < lstAdmins.Items.Count; i++)
        {
            if (lstAdmins.Items[i].Selected == true)
            {
                lstAdmins.Items.Remove(lstAdmins.Items[i]);
            }
        }
    }

    void btnAddUsers_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(empLookUp.value))
        {
            lblFieldAdminMsg.Visible = true;
            lblFieldAdminMsg.Text = "Invalid entry.";
            lblFieldAdminMsg.Style.Value = "color:red";
        }
        else if (lstAdmins.Items.FindByValue(empLookUp.value) == null)
        {
            lstAdmins.Items.Add(new ListItem(empLookUp.Text, empLookUp.value));
            empLookUp.Text = string.Empty;
        }
        else
        {
            //message for user already added 
            lblFieldAdminMsg.Visible = true;
            lblFieldAdminMsg.Text = "User already added.";
            lblFieldAdminMsg.Style.Value = "color:red";
        }
    }

    protected void wgData_PageIndexChanged(object sender, GridViewPageEventArgs e)
    {
        wgData.PageIndex = e.NewPageIndex;
        bindEventsGridView();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "setactivetab", "SetEventTab()", true);
    }

    void btnCreateEvent_Click(object sender, EventArgs e)
    {
        int eventid = 0;
        CMTEvent events = new CMTEvent();
        TimeSpan starttime = new TimeSpan(int.Parse(ddlStartTimeHrs.SelectedItem.Text), int.Parse(ddlStartTimeMns.SelectedItem.Text), 0);
        TimeSpan endtime = new TimeSpan(int.Parse(ddlEndhour.SelectedItem.Text), int.Parse(ddlEndMinute.SelectedItem.Text), 0);
        DateTime stardate = Convert.ToDateTime(txtStartDate.Text).Add(starttime);
        DateTime enddate = Convert.ToDateTime(txtEndDate.Text).Add(endtime);

        string message = string.Empty;
        XElement xExtendedAttribute;
        XDocument fieldadmins = new XDocument();
        XElement xRoot = new XElement("FieldAdmins");
        fieldadmins.Add(xRoot);
        foreach (ListItem item in lstAdmins.Items)
        {
            xExtendedAttribute = new XElement("FieldAdmin");
            xExtendedAttribute.Add(new XElement("GUI", item.Value));
            xExtendedAttribute.Add(new XElement("UserName", item.Text));
            xRoot.Add(xExtendedAttribute);
        }
        #region Field Admin Impleemntation

        string strGroupId = string.Empty;
        Settings loSetting = new Settings(Connection.SourceDataBase.CMT);
        strGroupId = loSetting["Security FieldAdmin GroupId"].ToString();

        if (String.IsNullOrEmpty(hdnFieldEventID.Value) || hdnFieldEventID.Value.Equals("0")) // Add
        {
            foreach (ListItem item in lstAdmins.Items)
            {
                Objects.Security.SecurityUserRight objUserRights = new Objects.Security.SecurityUserRight();
                CCollection loCollUserRights = new CCollection(objUserRights, "GUI=" + item.Value + " and " + "GroupId=" + strGroupId, true);
                DataTable dtUserRights = loCollUserRights.DataTable;

                if (dtUserRights.Rows.Count == 0)
                {
                    objUserRights = new Objects.Security.SecurityUserRight();
                    objUserRights.GUI = item.Value;
                    objUserRights.GroupID = Convert.ToInt32(strGroupId);
                    objUserRights.ExpirationDate = enddate;
                    objUserRights.Groups = "Added Filed Admin Role for CMT App";
                    objUserRights.Exception = false;
                    objUserRights.Save();
                }
            }
        }
        else //Update
        {
            DataTable dt = events.GetFieldAdminUpdateList(fieldadmins.ToString(), int.Parse(hdnFieldEventID.Value), Convert.ToDateTime(txtEndDate.Text).Add(endtime));
            foreach (DataRow dr in dt.Rows)
            {
                Objects.Security.SecurityUserRight objUserRights = new Objects.Security.SecurityUserRight();
                CCollection loCollUserRights = new CCollection(objUserRights, "GUI=" + dr["GUI"].ToString() + " and " + "GroupId=" + strGroupId, true);
                DataTable dtUserRights = loCollUserRights.DataTable;
                if (dtUserRights.Rows.Count == 0)
                {
                    objUserRights = new Objects.Security.SecurityUserRight();
                    objUserRights.GUI = dr["GUI"].ToString();
                    objUserRights.GroupID = Convert.ToInt32(strGroupId);
                    objUserRights.ExpirationDate = Convert.ToDateTime(dr["EndDate"].ToString());
                    objUserRights.Groups = "Added Filed Admin Role for CMT App";
                    objUserRights.Exception = false;
                    objUserRights.Save();
                }
                else
                {
                    Objects.Security.SecurityUserRight objUserRightsManupulate = new Objects.Security.SecurityUserRight(Convert.ToInt32(dtUserRights.Rows[0]["RightsID"]));

                    if (dr["Status"].ToString().Trim() == "D")
                    {
                        objUserRightsManupulate.Delete();
                    }
                    else if (dr["Status"].ToString().Trim() == "U")
                    {
                        objUserRightsManupulate.GUI = dr["GUI"].ToString();
                        objUserRightsManupulate.GroupID = Convert.ToInt32(strGroupId);
                        objUserRightsManupulate.ExpirationDate = Convert.ToDateTime(dr["EndDate"].ToString());
                        objUserRightsManupulate.Exception = false;
                        objUserRightsManupulate.Groups = "Updated  Field Admin Role for CMT App";
                        objUserRightsManupulate.Save();
                    }
                }
            }
        }
        #endregion

        if (DateTime.Compare(stardate, enddate) < 0)
        {
            if (String.IsNullOrEmpty(hdnFieldEventID.Value) || hdnFieldEventID.Value.Equals("0"))
            {
                message = events.AddEvent(txtEventName.Text, txtEventDescription.Text, ddlTimeZones.SelectedItem.Value, ddlTimeZones.SelectedItem.Text,
                    ddlCountry.SelectedItem.Value, stardate, enddate, int.Parse(CurrentUser.GUI), fieldadmins.ToString(), ref eventid, string.Empty);
                hdnFieldEventID.Value = eventid.ToString();
                bindQuestions();
            }
            else
            {
                message = events.UpdateEvent(int.Parse(hdnFieldEventID.Value), txtEventName.Text, txtEventDescription.Text, ddlTimeZones.SelectedItem.Value,
                    ddlTimeZones.SelectedItem.Text, ddlCountry.SelectedItem.Value, Convert.ToDateTime(txtStartDate.Text).Add(starttime),
                    Convert.ToDateTime(txtEndDate.Text).Add(endtime), int.Parse(CurrentUser.GUI), fieldadmins.ToString(), string.Empty);
            }
            lblEventMessage.Visible = true;
            if (message.ToLower().Contains("error") || message.ToLower().Contains("already exists"))
            {
                lblEventMessage.ForeColor = Color.Red;
            }
            else
            {
                lblEventMessage.ForeColor = Color.Green;
                bindEventsGridView(); //refersh grid
            }
            lblEventMessage.Text = message;
            div_Attendee.Visible = true;
            wgAttendeeDiv.Visible = Convert.ToBoolean(ViewState["isAttendeesExist"]);
        }
        else if (DateTime.Compare(stardate, enddate) > 0)
        {
            custStartEndDate.IsValid = false;
        }
        else
        {
            custEqStatEndDate.IsValid = false;
        }
    }

    void btnSearch_Click(object sender, EventArgs e)
    {
        wgData.PageIndex = 0;
        bindEventsGridView();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "setactivetab", "SetEventTab()", true);
    }

    void btnClear_Click(object sender, EventArgs e)
    {
        txtEventName.Text = "";
        txtEventDescription.Text = "";
        txtStartDate.Text = "";
        txtEndDate.Text = "";
        ddlTimeZones.SelectedIndex = 0;
        ddlCountry.SelectedIndex = 0;
        lstAdmins.Items.Clear();
        hdnFieldEventID.Value = "";
        btnCreateEvent.Text = "Save Event";
        clearRoom();
        ClearSearchAttendee();
        ClearUploadAttendee();
        ClearAttendeeEdit();
        div_Attendee.Visible = false;
        empLookUp.Text = string.Empty;
        empLookUp.value = string.Empty;
        ddlStartTimeHrs.ClearSelection();
        ddlStartTimeMns.ClearSelection();
        ddlEndhour.ClearSelection();
        ddlEndMinute.ClearSelection();

        ViewState["isQuestionConfigured"] = null;
        ViewState["isAttendeesExist"] = null;
        setRegistrationButtonVisibility();

        uwgEventRooms.Visible = false;
        btnDeleteRoom.Visible = false;
    }

    void btnClearEventSearch_Click(object sender, EventArgs e)
    {
        txt2EventName.Text = string.Empty;
        txt2StartDate.Text = string.Empty;
        txt2EndDate.Text = string.Empty;
        ddl2Country.SelectedIndex = 0;
        wgData.DataSource = null;
        wgDataDiv.Visible = false;
        ScriptManager.RegisterStartupScript(this, this.GetType(), "setactivetab", "SetEventTab()", true);
    }

    void GetEvents()
    {
        CMTEvent events = new CMTEvent();
        DateTime stardate = new DateTime();
        DateTime enddate = new DateTime();

        TimeSpan starttime = new TimeSpan(int.Parse(ddl2StartTimeHrs.SelectedItem.Text), int.Parse(ddl2StartTimemins.SelectedItem.Text), 0);
        TimeSpan endtime = new TimeSpan(int.Parse(ddl2EndTimeHrs.SelectedItem.Text), int.Parse(ddl2EndTimemins.SelectedItem.Text), 0);
        if (!string.IsNullOrEmpty(txt2StartDate.Text))
        {
            stardate = Convert.ToDateTime(txt2StartDate.Text).Add(starttime);
        }
        else
        {
            stardate = DateTime.MinValue;
        }

        if (!string.IsNullOrEmpty(txt2EndDate.Text))
        {
            enddate = Convert.ToDateTime(txt2EndDate.Text).Add(endtime);
        }
        else
        {
            enddate = DateTime.MinValue;
        }

        eventstable = events.GetEventDetails(txt2EventName.Text, ddl2Country.SelectedItem.Value, stardate, enddate, CurrentUser.GUI);
    }

    void bindEventsGridView()
    {
        GetEvents();
        if (eventstable.Rows.Count > 0)
        {
            wgDataDiv.Visible = true;
            wgData.DataSource = eventstable;
            wgData.DataBind();
        }
        else
        {
            wgDataDiv.Visible = false;
        }
    }

    private void setRegistrationButtonVisibility()
    {
        bool isQuestionConfigured = Convert.ToBoolean(ViewState["isQuestionConfigured"]);
        bool isAttendeesExist = Convert.ToBoolean(ViewState["isAttendeesExist"]);

        btnMail.Visible = isAttendeesExist & isQuestionConfigured;
        btnMailClient.Visible = isAttendeesExist;
    }
    #endregion

    #region Event attendee
    private void btnSearchAttendee_Click(object sender, EventArgs e)
    {
        bindAttendee();
    }

    protected void wgAttendee_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            bool isClient = Convert.ToBoolean(((CheckBox)e.Row.FindControl("chkIsClient")).Checked.ToString());
            if (isClient)
            {
                LinkButton lnkCalendar = e.Row.FindControl("lnkSendCalendar") as LinkButton;
                lnkCalendar.Enabled = false;
                lnkCalendar.ToolTip = string.Empty;
            }

        }
    }

    protected void wgAttendee_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        wgAttendee.PageIndex = e.NewPageIndex;
        bindAttendee();
    }

    protected void wgAttendee_ItemCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditAttendee")
        {
            GridViewRow row = ((Control)(e.CommandSource)).NamingContainer as GridViewRow;

            int eventattendeeId = Convert.ToInt32(((Label)row.FindControl("lblEventAttendeeID")).Text.ToString());
            bool canUpdateAllFields = canUpdateAttendee(eventattendeeId);
            hdneventattendee.Value = eventattendeeId.ToString();

            //change tab for edit attendee
            ScriptManager.RegisterStartupScript(this, this.GetType(), "setSelectedTab", "SetAttendeeSelectedTab(2)", true);

            // Retrieve row information
            txtFirstName.Text = decodeString(((Label)row.FindControl("lblFirstName")).Text);
            txtLastName.Text = decodeString(((Label)row.FindControl("lblLastName")).Text);
            txtEmailAddress.Text = decodeString(((Label)row.FindControl("lblEmailAddress")).Text);

            ListItem selectedListItem = ddlSalutation.Items.FindByValue(((Label)row.FindControl("lblSalutation")).Text);
            if (selectedListItem != null)
            {
                ddlSalutation.ClearSelection();
                selectedListItem.Selected = true;
            }

            txtPrefAddress.Text = decodeString(((Label)row.FindControl("lblPrefFormOfAddress")).Text);
            txtOffice.Text = decodeString(((Label)row.FindControl("lblOffice")).Text);
            txtCity.Text = decodeString(((Label)row.FindControl("lblCity")).Text);
            txtDirectDial.Text = decodeString(((Label)row.FindControl("lblDirectDial")).Text);
            txtMobileNumber.Text = decodeString(((Label)row.FindControl("lblMobileNumber")).Text);
            txtAssistantName.Text = decodeString(((Label)row.FindControl("lblAssistantName")).Text);
            txtAssistantNumber.Text = decodeString(((Label)row.FindControl("lblAssistantNumber")).Text);
            txtAssistantEmail.Text = decodeString(((Label)row.FindControl("lblAssistantEmail")).Text);

            DateTime start = string.IsNullOrEmpty(((Label)row.FindControl("lblAvailStartDate")).Text) ? DateTime.MinValue : Convert.ToDateTime(((Label)row.FindControl("lblAvailStartDate")).Text);
            ddlAvailableStartTimeHrs.ClearSelection();
            ddlAvailableStartTimeMns.ClearSelection();
            if (!start.Equals(DateTime.MinValue))
            {
                txtAvailableStartDate.Text = start.ToString("MMMM d, yyyy");
                ListItem starthr = ddlAvailableStartTimeHrs.Items.FindByValue(start.ToString("HH"));
                if (starthr != null)
                {
                    starthr.Selected = true;
                }

                ListItem startmm = ddlAvailableStartTimeMns.Items.FindByValue(start.ToString("mm"));
                if (startmm != null)
                {
                    startmm.Selected = true;
                }
            }
            else
            {
                txtAvailableStartDate.Text = string.Empty;
            }

            DateTime end = string.IsNullOrEmpty(((Label)row.FindControl("lblAvailEndDate")).Text) ? DateTime.MinValue : Convert.ToDateTime(((Label)row.FindControl("lblAvailEndDate")).Text);
            ddlAvailableEndTimeHrs.ClearSelection();
            ddlAvailableEndTimemm.ClearSelection();
            if (!end.Equals(DateTime.MinValue))
            {
                txtAvailableEndDate.Text = end.ToString("MMMM d, yyyy");
                ListItem endhr = ddlAvailableEndTimeHrs.Items.FindByValue(end.ToString("HH"));
                if (endhr != null)
                {
                    endhr.Selected = true;
                }

                ListItem endmm = ddlAvailableEndTimemm.Items.FindByValue(end.ToString("mm"));
                if (endmm != null)
                {
                    endmm.Selected = true;
                }
            }
            else
            {
                txtAvailableEndDate.Text = string.Empty;
            }


            bindCountryList();

            lstCountryRepresent.Items.Clear();
            if (!string.IsNullOrEmpty(Convert.ToString(((Label)row.FindControl("lblCountry")).Text)))
            {
                string[] countries = ((Label)row.FindControl("lblCountry")).Text.Split(',');
                foreach (string country in countries)
                {
                    foreach (ListItem cntryItem in lstCountry.Items)
                    {
                        if (cntryItem.Text == country.Trim())
                        {
                            lstCountryRepresent.Items.Add(cntryItem);
                        }
                    }
                    foreach (ListItem cntryItem in lstCountryRepresent.Items)
                    {
                        lstCountry.Items.Remove(cntryItem);
                    }
                }
                if (lstCountryRepresent.Items.Count > 0)
                {
                    lstCountryRepresent.Items[0].Selected = true;
                }
            }

            DateTime regDate = string.IsNullOrEmpty(((Label)row.FindControl("lblRegistrationDate")).Text) ? DateTime.MinValue : Convert.ToDateTime(((Label)row.FindControl("lblRegistrationDate")).Text);
            if (!regDate.Equals(DateTime.MinValue))
            {
                txtRegistrationDate.Text = regDate.ToString("MMMM d, yyyy");
            }
            else
            {
                txtRegistrationDate.Text = string.Empty;
            }
            txtSpecialityArea.Text = decodeString(((Label)row.FindControl("lblSpecialtyArea")).Text);

            bool visareq = Convert.ToBoolean(((Label)row.FindControl("lblVisaRequired")).Text);
            ddlVisaRequired.SelectedValue = (visareq ? OWN_YES : OWN_NO);

            bool confirmAttendance = Convert.ToBoolean(((Label)row.FindControl("lblConfirmationOfAttendance")).Text);
            ddlConfirmation.SelectedValue = (confirmAttendance ? OWN_YES : OWN_NO);

            bool isClient = Convert.ToBoolean(((CheckBox)row.FindControl("chkIsClient")).Checked);
            ddlClient.SelectedValue = (isClient ? OWN_CLIENT : OWN_PARTICIPANT);
            bool isRegMailSent = Convert.ToBoolean(((Label)row.FindControl("lblIsRegMailSent")).Text);

            setDisplayFieldsofClient(isClient);
            if (isClient)
            {
                txtCountryIssues.Text = decodeString(((Label)row.FindControl("lblCountryIssuesAddressed")).Text);
                bool sessionreq = Convert.ToBoolean(((Label)row.FindControl("lblComplimentaryPrivateSessionReq")).Text);
                ddlPrivateSession.SelectedValue = (sessionreq ? OWN_YES : OWN_NO);
            }
            else
            {
                txtCountryIssues.Text = decodeString(((Label)row.FindControl("lblCountryIssuesAddressed")).Text);
                bool hasFeedbackMail = Convert.ToBoolean(((Label)row.FindControl("lblFeedbackRequired")).Text);
                ddlSendFeedback.SelectedValue = (hasFeedbackMail ? OWN_YES : OWN_NO);

                bool isHost = Convert.ToBoolean(((Label)row.FindControl("lblIsHost")).Text);
                ddlHost.SelectedValue = (isHost ? OWN_YES : OWN_NO);
            }

            btnAddAttendee.Text = "Update Attendee";
            setEnabledFieldsOfAttendee(canUpdateAllFields, isRegMailSent);

            if (!canUpdateAllFields)
            {
                lbAddAttendee.Visible = true;
                lbAddAttendee.ForeColor = Color.Red;
                lbAddAttendee.Text = "Since the attendee is already scheduled for meeting(s), you will not be allowed to edit the disabled fields.";
            }
            pnlAttendeeNew.Enabled = true;
            tblAttendeeNew.Visible = false;
            bindAttendee();

        }
        if (e.CommandName.Equals("calendar"))
        {
            EventAttendee eventAttendee = new EventAttendee();
            GridViewRow row = ((Control)(e.CommandSource)).NamingContainer as GridViewRow;
            int eventattendeeId = Convert.ToInt32(((Label)row.FindControl("lblEventAttendeeID")).Text.ToString());
            bool isClient = Convert.ToBoolean(((CheckBox)row.FindControl("chkIsClient")).Checked);
            lblSearchAttendee.Visible = true;
            if (isClient)
            {
                lblSearchAttendee.ForeColor = Color.Red;
                lblSearchAttendee.Text = "Not allowed to send calendar since the selected attendee is not an participant.";
            }
            else if (eventAttendee.SendCalendarMail(eventattendeeId))
            {
                lblSearchAttendee.ForeColor = Color.Green;
                lblSearchAttendee.Text = "Meeting details are sent to the attendee.";
            }
            else
            {
                lblSearchAttendee.ForeColor = Color.Red;
                lblSearchAttendee.Text = "An exception occured on sending meeting details to the attendee.";
            }

        }

    }

    #endregion

    private void setDisplayFieldsofClient(bool isClient)
    {
        if (isClient)
        {
            trSendFeedback.Style.Value = "display:none";
            trHost.Style.Value = "display:none";

            trIssuesDiscussion.Style.Value = "display:inline";
            trPrivateSession.Style.Value = "display:inline";
        }
        else
        {
            trSendFeedback.Style.Value = "display:inline";
            trHost.Style.Value = "display:inline";

            trIssuesDiscussion.Style.Value = "display:none";
            trPrivateSession.Style.Value = "display:none";
        }
    }

    private void btnClearAttendee_Click(object sender, EventArgs e)
    {
        ClearAttendeeEdit();
    }

    private void bindAttendee()
    {
        if (!String.IsNullOrEmpty(hdnFieldEventID.Value.ToString()))
        {
            EventAttendee attendee = new EventAttendee();
            eventattendee = attendee.GetEventAttendee(txtSFirstName.Text, txtSLastName.Text, int.Parse(hdnFieldEventID.Value.ToString()));
            if (eventattendee.Rows.Count > 0)
            {
                wgAttendeeDiv.Visible = true;
                btnDeleteAttendee.Visible = true;
                wgAttendee.DataSource = eventattendee;
                wgAttendee.DataBind();

                ViewState["isAttendeesExist"] = true;
                setRegistrationButtonVisibility();
            }
            else
            {
                wgAttendeeDiv.Visible = false;
                btnDeleteAttendee.Visible = false;
                lblSearchAttendee.Visible = true;
                lblSearchAttendee.ForeColor = Color.Red;
                lblSearchAttendee.Text = "There are no attendee with the specified search parameters for selected event";

                ViewState["isAttendeesExist"] = false;
                setRegistrationButtonVisibility();
            }
        }
        else
        {
            lblSearchAttendee.Visible = true;
            lblSearchAttendee.Text = "Please select an event against attendee to be uploaded";
            lblSearchAttendee.ForeColor = Color.Red;
        }
    }

    private void btnAddAttendee_Click(object sender, EventArgs e)
    {
        saveAttendee(false);
    }

    protected void btnConfirmYes_Click(object sender, EventArgs e)
    {
        saveAttendee(true);
    }

    protected void btnConfirmNo_Click(object sender, EventArgs e)
    {
        pnlAttendeeNew.Enabled = true;
        tblAttendeeNew.Visible = false;
    }

    private void saveAttendee(bool forceSave)
    {
        pnlAttendeeNew.Enabled = true;
        tblAttendeeNew.Visible = false;

        DateTime stardate = new DateTime();
        DateTime enddate = new DateTime();
        DateTime regdate = new DateTime();

        TimeSpan starttime = new TimeSpan(int.Parse(ddlAvailableStartTimeHrs.SelectedItem.Text), int.Parse(ddlAvailableStartTimeMns.SelectedItem.Text), 0);
        TimeSpan endtime = new TimeSpan(int.Parse(ddlAvailableEndTimeHrs.SelectedItem.Text), int.Parse(ddlAvailableEndTimemm.SelectedItem.Text), 0);

        //start or end date or both can be empty.
        if (!string.IsNullOrEmpty(txtAvailableStartDate.Text))
        {
            stardate = Convert.ToDateTime(txtAvailableStartDate.Text).Add(starttime);
        }
        else
        {
            ddlAvailableStartTimeHrs.ClearSelection();
            ddlAvailableStartTimeMns.ClearSelection();
        }
        if (!string.IsNullOrEmpty(txtAvailableEndDate.Text))
        {
            enddate = Convert.ToDateTime(txtAvailableEndDate.Text).Add(endtime);
        }
        else
        {
            ddlAvailableEndTimeHrs.ClearSelection();
            ddlAvailableEndTimemm.ClearSelection();
        }

        if (!enddate.Equals(DateTime.MinValue))
        {
            if (DateTime.Compare(enddate, DateTime.Now) <= 0)
            {
                custAttendeDate.ErrorMessage = "Available End date should be future dates and not past dates";
                custAttendeDate.IsValid = false;
                return;
            }
            if (!stardate.Equals(DateTime.MinValue))
            {
                if (DateTime.Compare(stardate, enddate) > 0)
                {
                    custAttendeDate.ErrorMessage = "Available start date is later than end date.";
                    custAttendeDate.IsValid = false;
                    return;
                }
                else if (DateTime.Compare(stardate, enddate) == 0)
                {
                    custAttendeDate.ErrorMessage = "Available start date is same as end date. ";
                    custAttendeDate.IsValid = false;
                    return;
                }
            }
        }

        int success;
        string message = string.Empty;
        StringBuilder countryrepresent = new StringBuilder();

        for (int i = 0; i < lstCountryRepresent.Items.Count; i++)
        {
            countryrepresent.Append(lstCountryRepresent.Items[i].Text);
            if (i < lstCountryRepresent.Items.Count - 1)
            {
                countryrepresent.Append(",");
            }
        }

        bool visareq = false;
        if (ddlVisaRequired.SelectedItem.Text.ToUpper() == "YES")
        {
            visareq = true;
        }
        else if (ddlVisaRequired.SelectedItem.Text.ToUpper() == "NO")
        {
            visareq = false;
        }

        bool compreq = false;
        if (ddlPrivateSession.SelectedItem.Text.ToUpper() == "YES")
        {
            compreq = true;
        }
        else if (ddlPrivateSession.SelectedItem.Text.ToUpper() == "NO")
        {
            compreq = false;
        }

        bool confirm = false;
        if (ddlConfirmation.SelectedItem.Text.ToUpper() == "YES")
        {
            confirm = true;
        }
        else if (ddlConfirmation.SelectedItem.Text.ToUpper() == "NO")
        {
            confirm = false;
        }

        bool isClient = false;
        if (ddlClient.SelectedItem.Text.Equals(OWN_CLIENT))
        {
            isClient = true;
        }
        else if (ddlConfirmation.SelectedItem.Text.Equals(OWN_PARTICIPANT))
        {
            isClient = false;
        }

        bool feedbackRequired = false;
        bool isHost = false;
        if (!isClient)
        {
            if (ddlSendFeedback.SelectedItem.Text.ToUpper().Equals("YES"))
            {
                feedbackRequired = true;
            }

            if (ddlHost.SelectedItem.Text.ToUpper().Equals("YES"))
            {
                isHost = true;
            }
            txtCountryIssues.Text = string.Empty;
        }

        if (string.IsNullOrEmpty(txtRegistrationDate.Text) == false)
        {
            regdate = Convert.ToDateTime(txtRegistrationDate.Text);
        }

        EventAttendee attendee = new EventAttendee();
        //check for add or edit mode
        if (string.IsNullOrEmpty(hdneventattendee.Value.ToString()) == true)
        {
            if (string.IsNullOrEmpty(hdnFieldEventID.Value.ToString()) == false)
            {
                message = attendee.AddAttendee(int.Parse(hdnFieldEventID.Value.ToString()), txtFirstName.Text, txtLastName.Text, ddlSalutation.SelectedItem.Text
                    , txtPrefAddress.Text, txtEmailAddress.Text, txtOffice.Text, txtCity.Text, txtDirectDial.Text, txtMobileNumber.Text, txtAssistantName.Text
                    , txtAssistantEmail.Text, txtAssistantNumber.Text, visareq, stardate, enddate, compreq, txtCountryIssues.Text, regdate, confirm, txtSpecialityArea.Text
                    , countryrepresent.ToString(), isClient, feedbackRequired, isHost);

                if (message.ToLower().Contains("error") || message.ToLower().Contains("exists"))
                {
                    lbAddAttendee.ForeColor = Color.Red;
                    setDisplayFieldsofClient(isClient);
                }
                else
                {
                    lbAddAttendee.ForeColor = Color.Green;
                    ClearAttendeeEdit();
                }
                lbAddAttendee.Visible = true;
                lbAddAttendee.Text = message;
            }
            else
            {
                custAttendeDate.ErrorMessage = "Please select and event against attendee should be uploaded";
                custAttendeDate.IsValid = false;
            }
        }
        else
        { //edit mode
            string stardateString = (stardate.Equals(DateTime.MinValue) ? "" : stardate.ToString("yyyy-MM-dd HH:mm:ss"));
            string enddateString = (enddate.Equals(DateTime.MinValue) ? "" : enddate.ToString("yyyy-MM-dd HH:mm:ss"));

            //if (attendee.CanEditAttendeeAvilability(int.Parse(hdneventattendee.Value), stardateString, enddateString))
            string availabilityMsg = string.Empty;
            if (!forceSave)
            {
                availabilityMsg = attendee.CanEditAttendeeAvilability(int.Parse(hdneventattendee.Value), stardateString, enddateString);
            }

            if (availabilityMsg.Equals(string.Empty))
            {
                success = attendee.ModifyAttendee(int.Parse(hdneventattendee.Value), txtFirstName.Text, txtLastName.Text, ddlSalutation.SelectedItem.Text, txtPrefAddress.Text
                    , txtEmailAddress.Text, txtOffice.Text, txtCity.Text, txtDirectDial.Text, txtMobileNumber.Text, txtAssistantName.Text, txtAssistantEmail.Text
                    , txtAssistantNumber.Text, visareq, stardate, enddate, compreq, txtCountryIssues.Text, regdate, confirm, txtSpecialityArea.Text, countryrepresent.ToString()
                    , isClient, feedbackRequired, isHost);
                if (success > 0)
                {
                    lbAddAttendee.Visible = true;
                    lbAddAttendee.ForeColor = Color.Green;
                    lbAddAttendee.Text = "Attendee details updated successfully";
                }
                else
                {
                    lbAddAttendee.Visible = true;
                    lbAddAttendee.ForeColor = Color.Red;
                    lbAddAttendee.Text = "A conflict occured on saving the attendee";
                }
            }
            else
            {

                lblAttendeeNew.Text = availabilityMsg;
                pnlAttendeeNew.Enabled = false;
                tblAttendeeNew.Visible = true;
            }

            setDisplayFieldsofClient(isClient);
        }
        bindAttendee();
        ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "setSelectedAttendeeTab", "SetAttendeeSelectedTab(2)", true);
    }

    private void btnDeleteAttendee_Click(object sender, EventArgs e)
    {
        int attendeeeid = 0;
        int selectedRows = 0;
        int deletedRows = 0;
        EventAttendee eventattendee = new EventAttendee();
        CheckBox chkDelete = null;
        foreach (GridViewRow row in wgAttendee.Rows)
        {
            chkDelete = row.FindControl("chkDelete") as CheckBox;
            if (chkDelete.Checked)
            {
                //checked to del
                selectedRows++;
                attendeeeid = Convert.ToInt32(((Label)row.FindControl("lblEventAttendeeID")).Text);
                if (canUpdateAttendee(attendeeeid))
                {
                    // calls only for those attendee which are not assigned to a meeting
                    eventattendee.EventAttendeeID = attendeeeid;
                    eventattendee.Delete();
                    deletedRows++;
                }
            }
        }

        if (selectedRows > 0)
        {
            if (selectedRows == deletedRows)
            {
                // all selection successfully deleted
                lblSearchAttendee.Visible = true;
                lblSearchAttendee.Style.Value = "color:green;";
                lblSearchAttendee.Text = "All selected attendees successfully deleted.";
            }
            else if (deletedRows == 0)
            {
                // no rows could del since all are assigned to meeting
                lblSearchAttendee.Visible = true;
                lblSearchAttendee.Style.Value = "color:red;";
                lblSearchAttendee.Text = "Could not delete selected attendees since they are assigned to meeting.";
            }
            else
            {
                // could del only a few rows 
                lblSearchAttendee.Visible = true;
                lblSearchAttendee.Style.Value = "color:green;";
                lblSearchAttendee.Text = "Deleted only those attendees which have no meeting assigned.";
            }
        }
        else
        {
            // no rows selected. alert
            lblSearchAttendee.Visible = true;
            lblSearchAttendee.Style.Value = "color:red;";
            lblSearchAttendee.Text = "Please select atleast one attendee to delete.";
        }
        bindAttendee();
        ClearAttendeeEdit();
        if (wgAttendee.Rows.Count % 5 == 0 && wgAttendee.PageIndex > 0)
        {
            wgAttendee.PageIndex -= 1;
        }
    }

    private bool canUpdateAttendee(int attendeeid)
    {
        EventAttendee attendee = new EventAttendee();
        return !attendee.IsAttendeeAssignedToMeeting(attendeeid);
    }

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        DataTable failedinserts = new DataTable();

        EventAttendee eventattendee = new EventAttendee();
        string FilePath = string.Empty;
        string Format = string.Empty;
        string ext = string.Empty;
        int filelength = 0;
        int Positionofdot = 0;
        string Originalfilename = string.Empty;

        if (FileUploadControl.HasFile)
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            string temppath = Server.MapPath(@"~\UploadedFiles\\" + filename);
            try
            {
                FileUploadControl.SaveAs(temppath);

                FilePath = filename;
                filelength = FilePath.Length;
                Positionofdot = FilePath.LastIndexOf(".");
                Format = FilePath.Substring(Positionofdot + 1, (filelength - Positionofdot) - 1);

                Originalfilename = Path.GetFileNameWithoutExtension(FileUploadControl.FileName);

                if (Format.Equals("xls") || Format.Equals("xlsx"))
                {
                    ext = Format;
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "", "alert('Please upload .xls or .xlsx files only.'); ", true);
                    return;
                }

                XDocument xAttendeesdoc = readAttendeeExcelToXml(Format, temppath);
                if (!String.IsNullOrEmpty(hdnFieldEventID.Value.ToString()))
                {
                    string outMessage = string.Empty;
                    failedinserts = eventattendee.ImportAttendees(int.Parse(hdnFieldEventID.Value.ToString()), xAttendeesdoc.ToString(), ref outMessage);
                    //failed insert data log
                    if (failedinserts.Rows.Count > 0)
                    {
                        divAttendeeUpload.Visible = true;
                        lbFailedInsert.Visible = true;
                        lbFailedInsert.Text = string.Format("Couldn't insert {0} attendee rows", failedinserts.Rows.Count);
                        lbFailedInsert.Style.Value = "color:red;";
                        wgFailedRows.Visible = true;
                        wgFailedRows.DataSource = failedinserts;
                        wgFailedRows.DataBind();
                    }
                    else
                    {
                        lbUploadAttendee.Visible = true;
                        lbUploadAttendee.Text = outMessage;// "All attendee added against event";
                        lbUploadAttendee.Style.Value = "color:green;";
                    }
                }
                else
                {
                    lbUploadAttendee.Visible = true;
                    lbUploadAttendee.Text = "Please select an event against attendee to be uploaded";
                    lbUploadAttendee.Style.Value = "color:red;";
                }
            }
            catch (Exception ex)
            {
                StatusLabel.Visible = true;
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                StatusLabel.Style.Value = "color:red;";
            }
            File.Delete(temppath);
            bindAttendee();
            ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "setSelectedAttendeeTab", "SetAttendeeSelectedTab(1)", true);
        }
    }

    private static XDocument readAttendeeExcelToXml(string Format, string temppath)
    {
        string StrConnection = string.Empty;
        switch (Format)
        {
            case "xls":
                StrConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + temppath + "; Extended Properties=\"Excel 8.0;IMEX=1;\"";
                break;
            case "xlsx":
                StrConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" + temppath + "; Extended Properties=\"Excel 12.0 Xml;IMEX=1;\"";
                break;
        }

        DataSet dsAttendee = new DataSet();
        try
        {
            OleDbDataAdapter daAttendee = new OleDbDataAdapter("SELECT * FROM [" + "sheet1$A:AA]", StrConnection);
            daAttendee.Fill(dsAttendee);
        }
        catch (OleDbException ex)
        {
            throw new Exception("Invalid attendee upload template file, please ensure to use the template with required sheet(Sheet1) too.");
        }

        if (dsAttendee.Tables[0].Columns.Count != ATTENDEE_UPLOAD_COLUMN_COUNT)
        {// to hanlde the invalid excel template file. pls ensure this column count is same as of template file if it changes in future
            throw new Exception("Invalid attendee upload template file.");
        }
        XElement xAttendees;
        XDocument xAttendeesdoc = new XDocument();
        XElement xRoot = new XElement("Attendees");
        xAttendeesdoc.Add(xRoot);
        DataRow dr;
        for (int i = 0; i < dsAttendee.Tables[0].Rows.Count; i++)
        {
            dr = dsAttendee.Tables[0].Rows[i];
            xAttendees = new XElement("Attendee");

            xAttendees.Add(makeXElement(dr, "FirstName", 1));
            xAttendees.Add(makeXElement(dr, "LastName", 2));
            xAttendees.Add(makeXElement(dr, "Salutation", 3));
            xAttendees.Add(makeXElement(dr, "PrefFormOfAddress", 4));
            xAttendees.Add(makeXElement(dr, "EmailAddress", 5));
            xAttendees.Add(makeXElement(dr, "Office", 6));
            xAttendees.Add(makeXElement(dr, "City", 7));
            xAttendees.Add(makeXElement(dr, "Country", 8));
            xAttendees.Add(makeXElement(dr, "DirectDial", 9));
            xAttendees.Add(makeXElement(dr, "MobileNumber", 10));
            xAttendees.Add(makeXElement(dr, "AssistantName", 11));
            xAttendees.Add(makeXElement(dr, "AssistantNumber", 12));
            xAttendees.Add(makeXElement(dr, "AssistantEmail", 13));
            xAttendees.Add(makeXElement(dr, "VisaRequired", 14));
            xAttendees.Add(makeXElement(dr, "ComplimentaryPrivateSessionReq", 15));
            xAttendees.Add(makeXElement(dr, "CountryIssuesAddressed", 16));
            xAttendees.Add(makeXElement(dr, "RegistrationDate", 17));
            xAttendees.Add(makeXElement(dr, "ConfirmationOfAttendance", 18));
            xAttendees.Add(makeXElement(dr, "SpecialtyArea", 19));
            xAttendees.Add(makeXElement(dr, "AvailStartDate", 20));
            xAttendees.Add(makeXElement(dr, "AvailStartTime", 21));
            xAttendees.Add(makeXElement(dr, "AvailEndDate", 22));
            xAttendees.Add(makeXElement(dr, "AvailEndTime", 23));
            xAttendees.Add(makeXElement(dr, "IsClient", 24));
            xRoot.Add(xAttendees);
        }
        return xAttendeesdoc;
    }

    protected void btnLeft_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem country in lstCountryRepresent.Items)
            {
                if (country.Selected)
                {
                    lstCountry.Items.Add(country);
                }
            }

            foreach (ListItem country in lstCountry.Items)
            {
                lstCountryRepresent.Items.Remove(country);
            }

            if (lstCountryRepresent.Items.Count > 0)
            {
                lstCountryRepresent.SelectedIndex = 0;
            }
            setDisplayFieldsofClient(ddlClient.SelectedValue.Equals(OWN_CLIENT));
        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void btnAllLeft_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem country in lstCountryRepresent.Items)
            {
                lstCountry.Items.Add(country);
            }

            lstCountryRepresent.Items.Clear();
            setDisplayFieldsofClient(ddlClient.SelectedValue.Equals(OWN_CLIENT));
        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void btnAllRight_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem country in lstCountry.Items)
            {
                lstCountryRepresent.Items.Add(country);
            }

            lstCountry.Items.Clear();

            if (lstCountryRepresent.Items.Count > 0)
            {
                lstCountryRepresent.SelectedIndex = 0;
            }
            setDisplayFieldsofClient(ddlClient.SelectedValue.Equals(OWN_CLIENT));
        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void btnRight_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem country in lstCountry.Items)
            {
                if (country.Selected)
                {
                    lstCountryRepresent.Items.Add(country);
                }
            }

            foreach (ListItem country in lstCountryRepresent.Items)
            {
                lstCountry.Items.Remove(country);
            }

            if (lstCountryRepresent.Items.Count > 0)
            {
                lstCountryRepresent.SelectedIndex = 0;
            }
            setDisplayFieldsofClient(ddlClient.SelectedValue.Equals(OWN_CLIENT));
        }
        catch (Exception)
        {
            throw;
        }
    }

    private void bindCountryList()
    {
        CMTEvent events = new CMTEvent();
        lstCountry.DataSource = events.GetCountryDetails();
        lstCountry.DataTextField = "Description";
        lstCountry.DataValueField = "COUNTRY";
        lstCountry.DataBind();
    }

    private void ClearAttendeeEdit()
    {
        txtFirstName.Text = string.Empty;
        txtLastName.Text = string.Empty;
        txtPrefAddress.Text = string.Empty;
        txtEmailAddress.Text = string.Empty;
        txtOffice.Text = string.Empty;
        txtCity.Text = string.Empty;
        txtDirectDial.Text = string.Empty;
        txtDirectDial.Text = string.Empty;
        txtMobileNumber.Text = string.Empty;
        txtAssistantName.Text = string.Empty;
        txtAssistantEmail.Text = string.Empty;
        txtAssistantNumber.Text = string.Empty;
        txtAvailableStartDate.Text = string.Empty;
        txtAvailableEndDate.Text = string.Empty;
        txtCountryIssues.Text = string.Empty;
        txtRegistrationDate.Text = string.Empty;
        txtSpecialityArea.Text = string.Empty;
        hdneventattendee.Value = string.Empty;
        lbAddAttendee.Visible = false;
        btnAddAttendee.Text = "Add Attendee";

        setDisplayFieldsofClient(false);

        ddlSendFeedback.SelectedValue = OWN_NO;
        ddlHost.SelectedValue = OWN_NO;

        ddlSalutation.ClearSelection();
        ddlVisaRequired.ClearSelection();
        ddlPrivateSession.ClearSelection();
        ddlConfirmation.ClearSelection();
        ddlClient.ClearSelection();
        ddlAvailableStartTimeHrs.ClearSelection();
        ddlAvailableStartTimeMns.ClearSelection();
        ddlAvailableEndTimeHrs.ClearSelection();
        ddlAvailableEndTimemm.ClearSelection();

        lstCountryRepresent.Items.Clear();

        bindCountryList();
        setEnabledFieldsOfAttendee(true, false);
    }

    private void ClearSearchAttendee()
    {
        txtSFirstName.Text = "";
        txtSLastName.Text = "";
        lblSearchAttendee.Visible = false;
        btnDeleteAttendee.Visible = false;
        wgAttendeeDiv.Visible = false;
    }

    private void ClearUploadAttendee()
    {
        wgFailedRows.Visible = false;
        lbFailedInsert.Visible = false;
        lbUploadAttendee.Visible = false;
    }

    private void setEnabledFieldsOfAttendee(bool isEnabled, bool isRegMailSent)
    {
        txtEmailAddress.Enabled = isEnabled;
        ddlClient.Enabled = isEnabled && !isRegMailSent;// can update only no meeting scheduled and no reg mail sent
    }


    #region Rooms

    protected void btnClearRoom_Click(object sender, EventArgs e)
    {
        clearRoom();
    }

    protected void btnAddRoom_Click(object sender, EventArgs e)
    {
        Room room = new Room();
        int affected = 0;

        if (string.IsNullOrEmpty(hdnRoomId.Value))
        {
            affected = room.AddRoom(Convert.ToInt32(hdnFieldEventID.Value), txtRoomName.Text, txtRoomPhone.Text.Trim(), txtRoomCapacity.Text.Trim()
                , chkFlipCart.Checked, chkNetworkconnectors.Checked, chkWhiteboard.Checked, chkProjector.Checked, chkConfTelephone.Checked);
        }
        else
        {//update room
            affected = room.UpdateRoom(Convert.ToInt32(hdnFieldEventID.Value), Convert.ToInt32(hdnRoomId.Value), txtRoomName.Text, txtRoomPhone.Text.Trim(), txtRoomCapacity.Text.Trim()
                , chkFlipCart.Checked, chkNetworkconnectors.Checked, chkWhiteboard.Checked, chkProjector.Checked, chkConfTelephone.Checked);
        }
        if (affected > 0)
        {//success
            clearRoom();
            lblRoomMessage.Text = ROOM_SAVE; ;
            lblRoomMessage.Style.Value = "color:green;";
        }
        else
        {// show proper alert for err on add
            lblRoomMessage.Text = ROOM_NAME_EXIST;
            lblRoomMessage.Style.Value = "color:red;";
        }
        hdnSelectedRooms.Value = string.Empty;
        bindEventRooms();
    }

    protected void uwgEventRooms_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        uwgEventRooms.PageIndex = e.NewPageIndex;
        bindEventRooms();
        lblRoomMessage.Text = string.Empty;
    }

    protected void uwgEventRooms_ItemCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditRoom")
        {
            Room room = new Room();
            clearRoom();

            int roomId = Convert.ToInt32(e.CommandArgument);
            int eventId = Convert.ToInt32(hdnFieldEventID.Value);
            if (canUpdateRoom(roomId))
            {
                //edit room
                // Retrieve row information               
                DataTable dtRoomDetails = new Room().GetRoom(roomId);
                hdnRoomId.Value = roomId.ToString();
                if (dtRoomDetails.Rows.Count > 0)
                {
                    txtRoomName.Text = dtRoomDetails.Rows[0]["RoomNameNumber"].ToString();
                    txtRoomPhone.Text = dtRoomDetails.Rows[0]["PhoneNumber"].ToString();
                    txtRoomCapacity.Text = dtRoomDetails.Rows[0]["Capacity"].ToString();
                    chkFlipCart.Checked = Convert.ToBoolean(dtRoomDetails.Rows[0]["FlipChart"].ToString());
                    chkNetworkconnectors.Checked = Convert.ToBoolean(dtRoomDetails.Rows[0]["NetworkConnection"].ToString());
                    chkWhiteboard.Checked = Convert.ToBoolean(dtRoomDetails.Rows[0]["WhiteBoard"].ToString());
                    chkProjector.Checked = Convert.ToBoolean(dtRoomDetails.Rows[0]["Projector"].ToString());
                    chkConfTelephone.Checked = Convert.ToBoolean(dtRoomDetails.Rows[0]["ConfPhone"].ToString());
                }
                btnAddRoom.Text = "Update Room";
            }
            else
            {
                // blocked edit/delete
                lblRoomMessage.Style.Value = "color:red;";
                lblRoomMessage.Text = "You are not allowed to update the selected room, it is already assigned to a meeting.";
            }
        }
    }

    protected void uwgEventRooms_onRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkDel = e.Row.FindControl("chkDelete") as CheckBox;
            Label lblRoomId = e.Row.FindControl("lblRoomId") as Label;
            chkDel.Attributes.Add("onclick", "javascript:setRoomSelection(this," + lblRoomId.Text + ");");

            string[] roomSelection = hdnSelectedRooms.Value.TrimEnd(',').Split(',');
            if (roomSelection.Contains(lblRoomId.Text))
            {
                chkDel.Checked = true;
            }
        }
    }

    protected void btnDeleteRooms_Click(object sender, EventArgs e)
    {
        clearRoom();
        int selectedRows = 0;
        int deletedRows = 0;
        Room room = new Room();

        // using selected values on hdn field
        int[] roomSelection = hdnSelectedRooms.Value.TrimEnd(',').Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(rm => Convert.ToInt32(rm)).ToArray();
        selectedRows = roomSelection.Length;
        foreach (int roomId in roomSelection)
        {
            if (canUpdateRoom(roomId))
            {
                room.DeleteRoom(roomId);// calls only for those rooms which are not assigned to a meeting. so can direct delete 
                deletedRows++;
            }
        }

        if (selectedRows > 0)
        {
            if (selectedRows == deletedRows)
            {// all selection successfully deleted
                lblRoomMessage.Style.Value = "color:green;";
                lblRoomMessage.Text = "All selected room(s) successfully deleted.";
            }
            else if (deletedRows == 0)
            {// no rows could del since all are assigned to meeting
                lblRoomMessage.Style.Value = "color:red;";
                lblRoomMessage.Text = "Could not delete selected rooms since they are assigned to meeting.";
            }
            else
            {// could del only a few rows 
                lblRoomMessage.Style.Value = "color:green;";
                lblRoomMessage.Text = "Deleted only those rooms which have no meeting assigned.";
            }
        }
        else
        {// no rows selected. alert
            lblRoomMessage.Style.Value = "color:red;";
            lblRoomMessage.Text = "Please select atleast one room to delete.";
        }
        hdnSelectedRooms.Value = string.Empty;
        bindEventRooms();
    }

    private void clearRoom()
    {
        txtRoomName.Text = string.Empty;
        txtRoomPhone.Text = string.Empty;
        txtRoomCapacity.Text = string.Empty;
        chkFlipCart.Checked = false;
        chkNetworkconnectors.Checked = false;
        chkWhiteboard.Checked = false;
        chkProjector.Checked = false;
        chkConfTelephone.Checked = false;
        btnAddRoom.Text = "Add Room";
        hdnRoomId.Value = string.Empty;
        lblRoomMessage.Text = string.Empty;
    }

    private void bindEventRooms()
    {
        Room room = new Room();
        DataTable dtRooms = room.GetEventRooms(Convert.ToInt32(hdnFieldEventID.Value));
        uwgEventRooms.DataSource = dtRooms;
        uwgEventRooms.DataBind();
        if (dtRooms.Rows.Count > 0)
        {
            uwgEventRooms.Visible = true;
            btnDeleteRoom.Visible = true;
        }
        else
        {
            uwgEventRooms.Visible = false;
            btnDeleteRoom.Visible = false;
        }
    }

    private bool canUpdateRoom(int roomId)
    {
        Room room = new Room();
        return !room.IsRoomAssignedToMeeting(roomId);
    }

    #endregion

    #region Questions

    private void bindQuestions()
    {
        Questions questions = new Questions();
        questions.EventId = Convert.ToInt32(hdnFieldEventID.Value);
        DataTable dtEventQuestions = new CCollection(questions, true).DataTable;

        try
        {
            isQuestionsLocked = Convert.ToBoolean(dtEventQuestions.Select("IsLock=1").Count());
            if (dtEventQuestions.Select("IsMapped=1").Count().Equals(dtEventQuestions.Rows.Count))
            {
                btnSelectAll.Text = "Unselect All Questions";
            }
            else
            {
                btnSelectAll.Text = "Select All Questions";
            }
        }
        catch (Exception ex)
        {// just to avoid exception of empty table 
        }
        if (isQuestionsLocked)
        {
            btnSaveQuestions.Enabled = false;
            btnSelectAll.Enabled = false;
            lblQuestions.Text = "Question edit feature is blocked since the attendees have started registering.";
            lblQuestions.ForeColor = Color.Red;
            lblQuestions.Visible = true;
        }
        ugQuestions.DataSource = dtEventQuestions;
        ugQuestions.DataBind();
    }

    protected void ugQuestions_onRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkAdd = e.Row.FindControl("chkAddQuestion") as CheckBox;
            chkAdd.Enabled = !isQuestionsLocked;
        }
    }

    protected void btnSaveQuestions_Click(object sender, EventArgs e)
    {
        string qCodes = string.Empty;
        int checkedCount = 0;
        CheckBox chkAddQuestion = null;
        Label lblCode = null;
        foreach (GridViewRow row in ugQuestions.Rows)
        {
            chkAddQuestion = row.FindControl("chkAddQuestion") as CheckBox;
            if (chkAddQuestion.Checked)
            {
                lblCode = row.FindControl("lblCode") as Label;
                //checked to map the q to event
                qCodes += lblCode.Text + ",";
                checkedCount++;
            }
        }

        //string qCodes = string.Empty; // PLS ensure not allows edit on already answered Q
        //TemplatedColumn chkCol = ((TemplatedColumn)(ugQuestions.Columns.FromKey("selectQuestion")));

        //int checkedCount = 0;
        //foreach (GridViewRow ugRow in ugQuestions.Rows)
        //{
        //    CellItem item = ((CellItem)(chkCol.CellItems[ugRow.RowIndex]));
        //    if (((CheckBox)(item.FindControl("chkAddQuestion"))).Checked)
        //    {
        //        //checked to map the q to event
        //        qCodes += ugRow.Cells[2].GetText() + ",";
        //        checkedCount++;
        //    }
        //}
        ViewState["isQuestionConfigured"] = Convert.ToBoolean(checkedCount);

        //add the questions againt event
        Questions question = new Questions();
        string questXmlString = makeQuestionXml(qCodes.TrimEnd(',').Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
        if (question.MapQuestionsToEvent(Convert.ToInt32(hdnFieldEventID.Value), questXmlString, CurrentUser.GUI) > 0)
        {// all selection successfully saved. if rowsaffected  0 means already attendees started answering it
            lblQuestions.Visible = true;
            lblQuestions.ForeColor = Color.Green;
            lblQuestions.Text = QUESTION_SAVE;
        }

        bindQuestions();
        setRegistrationButtonVisibility();
    }

    private string makeQuestionXml(string[] qustCodes)
    {
        XDocument xDoc = new XDocument();
        XElement xRoot = new XElement("Questions");
        xDoc.Add(xRoot);

        XElement xQuestion;
        foreach (string questionCode in qustCodes)
        {
            xQuestion = new XElement("Question");
            xQuestion.Add(new XElement("Code", questionCode.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Trim()));
            xRoot.Add(xQuestion);
        }
        return xDoc.ToString();
    }

    #endregion

    #region participant registration

    protected void btnMail_Click(object sender, EventArgs e)
    {
        sendRegistrationMail(false);
    }

    protected void btnMailClient_Click(object sender, EventArgs e)
    {
        sendRegistrationMail(true);
    }

    private void sendRegistrationMail(bool isClient)
    {
        EventAttendee ownParticipant = new EventAttendee();

        DataTable dtStatus = ownParticipant.SendRegistrationMail(Convert.ToInt32(hdnFieldEventID.Value), (isClient ? 1 : 0));
        lblEventMessage.Text = dtStatus.Rows[0]["Messgae"].ToString();
        lblEventMessage.Visible = true;
        lblEventMessage.ForeColor = (Convert.ToBoolean(dtStatus.Rows[0]["Status"]) ? Color.Green : Color.Red);
    }
    #endregion

    private string decodeString(object toConvertObj)
    {
        return Server.HtmlDecode(Convert.ToString(toConvertObj).Trim());
    }

    private static XElement makeXElement(DataRow dr, string elemName, int colIndex)
    {
        return new XElement(elemName, HttpUtility.HtmlEncode(dr[colIndex].ToString().Trim()));
    }
}
